package com.ankang.service.impl;

import com.ankang.controller.DisplayManager;
import com.ankang.entity.ChannelLevel;
import com.ankang.service.ChannelLevelService;
import com.ankang.util.ModbusTcpClientTow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author mjiajia
 * @date 2025/9/1 16:25
 * @desciption
 */
@Service
public class DisplayService {


    private static final Logger log = LoggerFactory.getLogger(DisplayService.class);

    @Autowired
    private ChannelLevelService channelLevelService;

    /**
     * 系统启动时初始化所有显示器
     */
    @PostConstruct
    public void initAllDisplays() {
        log.info("系统启动，开始初始化所有通道显示器...");
        List<ChannelLevel> channels = channelLevelService.list();
        for (ChannelLevel channel : channels) {
            initDisplay(channel);
        }
        log.info("所有通道显示器初始化完成");
    }

    /**
     * 初始化单个通道显示器
     */
    public void initDisplay(ChannelLevel channel) {
        try {
            sendMess(channel);
            log.info("通道{}显示器初始化成功", channel.getChannelId());
        } catch (Exception e) {
            log.error("通道{}显示器初始化失败", channel.getChannelId(), e);
        }
    }

    /**
     * 更新通道显示器数据（配置变更时调用）
     */
    public void updateDisplay(ChannelLevel channel) {
        try {
            sendMess(channel);
            log.info("通道{}显示器数据已更新", channel.getChannelId());
        } catch (Exception e) {
            log.error("通道{}显示器数据更新失败", channel.getChannelId(), e);
        }
    }

    /**
     * 调用显示器显示信息
     * @param channel
     */
    private void sendMess(ChannelLevel channel){
        ModbusTcpClientTow modbusTcpClientTow = new ModbusTcpClientTow(channel);
        String message1;
        String message2 = null;

        // 判断是否包含英文逗号或中文逗号
        if (channel.getTargetGrade().contains(",") || channel.getTargetGrade().contains("，")) {
            // 使用正则表达式同时匹配中英文逗号，最多分割一次
            String[] parts = channel.getTargetGrade().split("[,，]", 2);
            message1 = parts[0];
            // 确保有第二部分再赋值
            if (parts.length > 1) {
                message2 = parts[1];
            }
        } else {
            // 不包含任何逗号，直接赋值给message1
            message1 = channel.getTargetGrade();
        }
        modbusTcpClientTow.sendMessages(message1,message2);
    }
}
